iT邦幫忙

2023 iThome 鐵人賽

DAY 25
0
SideProject30

行事曆不再NG:Notion API&Google Calendar跨平台整合發想系列 第 25

Day 25 Notion API & Google Calendar API Integration - Create Notion Page

  • 分享至 

  • xImage
  •  

一樣先上spec

/notion/createNotionDBPage/{databaseId}:
    post:
      summary: Create a new Notion Page
      parameters:
        - name: databaseId
          in: path
          required: true
          description: Update a database as specified by the parameters.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                properties:
                  type: object
                  description: JSON object defining create page properties
      responses:
        '200':
          description: Notion page create successfully
        '400':
          description: Invalid input

Main

這邊先把Router加上

func main() {
	r := gin.Default()

	c := controller.NewController()

	v1 := r.Group("/api/v1")
	{
		notion := v1.Group("/notion")
		{
			notion.POST("/createDatabase/:pageId", c.CreateNotionDatabase)
			notion.POST("/queryDatabase/:databaseId", c.QueryNotionDatabase)
			notion.POST("/createDBPage/:databaseId", c.CreateNotionDBPage)
		}
...

因為主要是createDB的page,所以先將Router設定成/createDBPage/:databaseId

再來來寫Controller

Controller

// Create a Page godoc
//
//	@Summary		Create a new Notion Page
//	@Description	Creates a new page in the specified database or as a child of an existing page.
//	@Tags			notion
//	@Accept			json
//	@Produce		json
//	@Param			databaseId	path	string	true	"Database ID"
//	@Param 			request body 	requestModel.NotionCreateDBPageRequest true	"Request Body"
//	@Success		200		{array}		responseModel.Database
//	@Failure		400		{string}	string			"Invalid input"
//	@Router			/api/v1/notion/createDBPage/{databaseId} [post]
func (c *Controller) CreateNotionDBPage(ctx *gin.Context) {
	// Get Authorization from config
	configHandler := util.NewConfigHandler()
	auth := configHandler.GetSecretConfig().Get("Authorization")

	databaseId := ctx.Param("databaseId")

	var requests requestModel.NotionCreateDBPageRequest
	if err := ctx.ShouldBindJSON(&requests); err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	propertiesJson, err := json.Marshal(requests.Properties)
	if err != nil {
		log.Fatalln(err)
	}

	// Send the request to Notion API
	client := handler.NewClient()
	header := map[string]string{
		"Authorization":  auth.(string),
		"Notion-Version": "2022-06-28",
		"Content-Type":   "application/json",
	}
	bodyString := `{
			"parent": {
				"database_id": "` + databaseId + `"
			},
			"properties": ` + string(propertiesJson) + ` 
		}`
	body := []byte(bodyString)

	response, err := client.Post("https://api.notion.com/v1/pages", header, body)
	if err != nil {
		log.Fatalln(err)
	}
	defer response.Body.Close()

	// Change the response body to []byte type
	responseBody, err := io.ReadAll(response.Body)
	if err != nil {
		log.Fatalln(err)
	}
	bodyStr := string(responseBody)
	var data []byte = []byte(bodyStr)

	// Unmarshal the response body to struct
	var responseCreateNotionDatabase responseModel.NotionCreateDatabaseResponse
	json.Unmarshal(data, &responseCreateNotionDatabase)

	ctx.JSON(http.StatusOK, responseCreateNotionDatabase)
}

內容和前幾天大同小異,這邊就不細講內容,直接上code

Request

type NotionCreateDBPageRequest struct {
	Properties map[string]interface{} `json:"properties"`
}

這邊要的參數就只有Properties而已,其他的參數在這個Side Project中用不到

可以參考https://developers.notion.com/reference/post-page這個頁面的BODY PARAMS

Response

Response的內容和前幾天的Database這個struct的內容一樣,這邊一樣先把code貼上來

type Database struct {
	Object         string `json:"object"`
	ID             string `json:"id"`
	CreatedTime    string `json:"created_time"`
	LastEditedTime string `json:"last_edited_time"`
	CreatedBy      struct {
		Object string `json:"object"`
		ID     string `json:"id"`
	} `json:"created_by"`
	LastEditedBy struct {
		Object string `json:"object"`
		ID     string `json:"id"`
	} `json:"last_edited_by"`
	Cover  interface{} `json:"cover"`
	Icon   interface{} `json:"icon"`
	Parent struct {
		Type       string `json:"type"`
		DatabaseID string `json:"database_id"`
	} `json:"parent"`
	Archived   bool                   `json:"archived"`
	Properties map[string]interface{} `json:"properties"`
	URL        string                 `json:"url"`
	PublicURL  interface{}            `json:"public_url"`
}

Demo

再來就直接進demo了

Body

{
    "properties": {
        "Title": [
            {
                "text": {
                    "content": "test1"
                }
            }
        ],
        "Date": {
            "start": "2023-10-09T12:00:00+08:00",
            "end": "2023-10-09T13:00:00+08:00"
        }
    }
}

Notion DB

https://ithelp.ithome.com.tw/upload/images/20231009/20140869TmpOep5Eh7.png

Response

{
  "object": "page",
  "id": "",
  "created_time": "2023-10-09T07:53:00.000Z",
  "last_edited_time": "2023-10-09T07:53:00.000Z",
  "url": "",
  "title": null,
  "properties": {
    "Date": {
      "date": {
        "end": "2023-10-09T13:00:00.000+08:00",
        "start": "2023-10-09T12:00:00.000+08:00",
        "time_zone": null
      },
      "id": "s%7D%5CP",
      "type": "date"
    },
    "Title": {
      "id": "title",
      "title": [
        {
          "annotations": {
            "bold": false,
            "code": false,
            "color": "default",
            "italic": false,
            "strikethrough": false,
            "underline": false
          },
          "href": null,
          "plain_text": "test1",
          "text": {
            "content": "test1",
            "link": null
          },
          "type": "text"
        }
      ],
      "type": "title"
    }
  },
  "parent": {
    "type": "database_id",
    "page_id": ""
  },
  "archived": false,
  "is_inline": false
}

上一篇
Day 24 Notion API & Google Calendar API Integration - Refactor Architecture and Spec
下一篇
Day 26 Notion API & Google Calendar API Integration - Google Calendar List Refactor
系列文
行事曆不再NG:Notion API&Google Calendar跨平台整合發想30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言